package com.pencilisland.pay.app.mp.service.impl;

import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.bean.mp.app.LastOrderAddressREQ;
import com.pencilisland.pay.api.bean.mp.app.LastOrderAddressRES;
import com.pencilisland.pay.api.bean.mp.app.MessageRequest;
import com.pencilisland.pay.api.bean.mp.app.MessageResponse;
import com.pencilisland.pay.api.bean.mp.app.WxPayUnifyOrderRES;
import com.pencilisland.pay.api.bean.wxpay.WxLoginResp;
import com.pencilisland.pay.api.entity.OrderAddressEntity;
import com.pencilisland.pay.api.repository.OrderAddressRepository;
import com.pencilisland.pay.api.service.CacheService;
import com.pencilisland.pay.app.mp.service.MBService;
/**
* 报文逻辑处理.查询当前用户的最新的收货地址
*
* @author breeze
*/
@Service("MB_lastOrderAddress")
public class  LastOrderAddressMB implements MBService {

	@Autowired
	ObjectMapper objectMapper;
	@Autowired
	CacheService cacheService;
	@Autowired
	OrderAddressRepository orderAddressRepo;

	@Override
	public MessageResponse process(MessageRequest request) {
		
		WxLoginResp result = (WxLoginResp) cacheService.get(request.getSessionId());
		if(result==null||StringUtils.isEmpty(result.getOpenId())){
			return new WxPayUnifyOrderRES(false, null, "没有登录数据");
		}
		
		LastOrderAddressRES res= new LastOrderAddressRES(true,null,"OK");
		
		List<OrderAddressEntity> orderAddressList = orderAddressRepo.findByOpenIdOrderByOrderTimeDesc(result.getOpenId());
		if(orderAddressList!=null&&!orderAddressList.isEmpty()){
			OrderAddressEntity orderAddress = orderAddressList.get(0);
			try {
				BeanUtils.copyProperties(res, orderAddress);
			} catch (Exception e) {
				e.printStackTrace();
			} 
		}
		
		return res;
	}
	
	public LastOrderAddressREQ getRequestBody(MessageRequest request){
		return objectMapper.convertValue(request.getBody(), LastOrderAddressREQ.class);
	}

}
